package com.mtiiot.fstcpserver.utils;

import java.util.Random;

/**
 * 随机码
 */
public class RandomCodeUtil
{
	//数字类型
	public final static int NUM_TYPE = 1;
	
	//字母类型
	public final static int LETTER_TYPE = 2;
	
	//混合类型
	public final static int BLEND_TYPE = 3;

    /**
	 * 生成邀请码
	 * @param length
	 * @return
	 */
	public static String getRandomCode(int length, int type)
	{
		String val = "";
		Random random = new Random();
		for (int i = 0; i < length; i++)
		{
			//获取单个字符的类型
			int charType = getCharType(type);
			if (charType == LETTER_TYPE) 
			{
				//字符类型
				// 取得大写字母还是小写字母
				int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; 
				val += (char) (choice + random.nextInt(26));
			} 
			else if (charType == NUM_TYPE) 
			{ 
				//数字类型
				val += String.valueOf(random.nextInt(10));
			}
		}
		return val;
	}
	
	/**
	 * 获取每个字符的类型
	 * @param type
	 * @return
	 */
	private static int getCharType(int type)
	{
		//纯数字类型
		if(type == NUM_TYPE)
		{
			return NUM_TYPE;
		}
		//纯字母类型
		if(type == LETTER_TYPE)
		{
			return LETTER_TYPE;
		}
		//混合类型
		if(type == BLEND_TYPE)
		{
			Random random = new Random();
			int charType = random.nextInt(2) % 2 == 0 ?  LETTER_TYPE : NUM_TYPE;
			return charType;
		}
		return NUM_TYPE;
	}
}
